using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Collections.Specialized;
using System.Text;
using System.Threading;
using System.Windows.Threading;
using ViewOnCore.Helper.WPF;

#region Copyright (c) 2006, 2007, 2008 ViewOn Media Services. All rights reserved.

/*
 Copyright (c) 2006, 2007, 2008 ViewOn Media Services. All rights reserved.
 This work is copyrighted in its entirety. Permission to use "ViewOn.tv"
 material may be granted only after we receive a written request from you,
 and you receive written permission from us.

 While ViewOn Media Services provides the information herein to anyone,
 we retain copyright on all code, text, graphic images, and other content.
 This means that you may not distribute the code, the text or graphics to others without the
 express written permission of ViewOn Media Services; "mirror" this information on your server
 without our permission; or modify or reuse the code, text or graphics on our servers.
 You may print copies of the information for your own personal use; and, you may reference
 the Service from your own documents. Any commercial use of this material is prohibited without
 the written permission of ViewOn Media Services. In all copies of this information, you must
 retain this notice and any other copyright notices originally included with such information.

 This material may be protected by U.S. and International Copyright laws, and you are legally
 bound by the copyright notices on those systems.

 "ViewOn" logos and other official symbols or graphics may not be used in connection with any
 product or service that has not been expressly authorized in advance in writing or in any manner
 that is likely to cause confusion among the users of this or other Web sites or among the public.
 All other seals, graphics or trademarks of organizations not affiliated with ViewOn Media Services
 that appear on this site are the property of their respective owners.

 ViewOn Media Services reserve all other rights. 
*/

#endregion

#region ViewOn.tv Source Code Licence

/*
This license governs use of the ViewOn.tv software. If you use the software, you accept this license. If you do not accept the license, do not use the software.

1. Summary

The source code is made available to view for reference purposes or to contribute to the project only. Developers may not distribute or modify the code for commercial or non-commercial purposes without express Agreement of View On Media Services.

2. Definitions

The terms "reproduce," "reproduction," and "distribution" have the same meaning here as under U.S. copyright law.
"Licensor" means the company "ViewOn Media Services".
"You" means the licensee of the software, who is not engaged in designing, developing, or testing other software, that has the same or substantially the same features or functionality as the software.
"Your company" means the company you worked for when you downloaded the software.
"Reference use" means use of the software within your company as a reference, in read only form, for the sole purposes of debugging and maintaining your products. For clarity, "reference use" does NOT include (a) the right to use the software for purposes of designing, developing, or testing other software, that has the same or substantially the same features or functionality as the software, and (b) the right to distribute the software outside of your company.
"Licensed patents" means any Licensor patent claims which read directly on the software as distributed by the Licensor under this license.

3. Grant of Rights

(A) Copyright Grant- Subject to the terms of this license, the Licensor grants you a non-transferable, non-exclusive, worldwide, royalty-free copyright license to reproduce the software for reference use.
(B) Patent Grant- Subject to the terms of this license, the Licensor grants you a non-transferable, non-exclusive, worldwide, royalty-free patent license under licensed patents for reference use.
4. Limitations
(A) No Trademark License- This license does not grant you any rights to use the Licensor's name, logo, or trademarks.
(B) If you begin patent litigation against the Licensor over patents that you think may apply to the software (including a cross-claim or counterclaim in a lawsuit), your license to the software ends automatically.
(C) The software is licensed "as-is." You bear the risk of using it. The Licensor gives no express warranties, guarantees or conditions. You may have additional consumer rights under your local laws which this license cannot change. To the extent permitted under your local laws, the Licensor excludes the implied warranties of merchantability, fitness for a particular purpose and non-infringement.
 */

#endregion

namespace ViewOnCore.Helper.Collection
{

    /// <summary>
    /// This collection has several special features like :
    /// - Lazy refresh : Only send the 'OnCollectionChanged' event every X added items.
    /// - Sortable
    /// - Find feature
    /// - Exists feature
    /// </summary>
    sealed public class ExtObservableCollection<T> : ObservableCollection<T>, IDisposable
    {

        #region Variables

        private List<T> _deferredList = new List<T>();

        private bool _lazyRefresh = false;
        private int _lazyRefreshGap = 10;

        /// <summary>
        /// Used to bypass the refresh event
        /// </summary>
        private bool _bypassRefreshEvent = false;

        #endregion

        #region Constructor

        public ExtObservableCollection()
        {
        }

        ~ExtObservableCollection()
        {
            Dispose();
        }

        #endregion

        #region IDisposable Members

        public void Dispose()
        {
            ForceRefresh();

            // Prevent the finalizer from running 
            GC.SuppressFinalize(this);
        }

        #endregion

        #region Exists

        /// <summary>
        /// Check if an item exist, based on a predicate.
        /// </summary>
        public bool Exists(Predicate<T> match)
        {
            return (FindIndex(match) != -1);
        }

        #endregion

        #region FindIndex

        /// <summary>
        /// Find based on a predicate.
        /// </summary>
        /// <returns>Returns the index, returns -1 if not found</returns>
        public int FindIndex(Predicate<T> match)
        {
            return FindIndex(0, Count, match);
        }

        /// <summary>
        /// Find based on a predicate.
        /// </summary>
        /// <returns>Returns the index, returns -1 if not found</returns>
        public int FindIndex(int startIndex, int count, Predicate<T> match)
        {
            //if (startIndex > this._size)
            //    ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.startIndex, ExceptionResource.ArgumentOutOfRange_Index);

            //if ((count < 0) || (startIndex > (this._size - count)))
            //    ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.count, ExceptionResource.ArgumentOutOfRange_Count);

            //if (match == null)
            //    ThrowHelper.ThrowArgumentNullException(ExceptionArgument.match);

            int num = startIndex + count;
            for (int i = startIndex; i < num; i++)
                if (match(this[i]))
                    return i;

            return -1;
        }

        #endregion

        #region Sort

        /// <summary>
        /// Sort the collection
        /// </summary>
        public void Sort()
        {
            Sort(Comparer<T>.Default);
        }

        /// <summary>
        /// Sort the collection based on a specific comparer.
        /// </summary>
        public void Sort(IComparer<T> comparer)
        {
            int i, j;
            T index;

            for (i = 1; i < Count; i++)
            {
                index = this[i];     //If you can't read it, it should be index = this[x], where x is i :-)
                j = i;

                while ((j > 0) && (comparer.Compare(this[j - 1], index) == 1))
                {
                    this[j] = this[j - 1];
                    j = j - 1;
                }

                this[j] = index;
            }
        }

        #endregion

        #region Properties

        /// <summary>
        /// Set/Gets the Lazy refresh mode, it mean that the 'OnCollectionChanged' event
        /// will not be raised for each added item but for each 'LazyRefreshGap' items.
        /// 
        /// You can use 'ForeRefresh' to force the call to the 'OnCollectionChanged' event.
        /// </summary>
        public bool LazyRefresh
        {
            get
            {
                return _lazyRefresh;
            }
            set
            {
                _lazyRefresh = value;
            }
        }

        /// <summary>
        /// Set/Gets the Lazy refresh gap, it mean that the 'OnCollectionChanged' event
        /// will not be raised for each added item but for each 'LazyRefreshGap' items.
        /// 
        /// You can use 'ForeRefresh' to force the call to the 'OnCollectionChanged' event.
        /// </summary>
        public int LazyRefreshGap
        {
            get
            {
                return _lazyRefreshGap;
            }
            set
            {
                _lazyRefreshGap = value;
            }
        }

        #endregion

        #region InsertItem

        protected override void InsertItem(int index, T item)
        {
            if (_lazyRefresh)
                _bypassRefreshEvent = true;

            base.InsertItem(index, item);

            if (_lazyRefresh)
                _bypassRefreshEvent = false;
            else
                return;

            _deferredList.Add(item);

            if ((_deferredList.Count % _lazyRefreshGap) == 0)
                ForceRefresh();
        }

        #endregion

        #region ForceRefresh

        /// <summary>
        /// Force the collection to call the 'OnCollectionChanged' if necessary.
        /// </summary>
        public void ForceRefresh()
        {
            if (_deferredList.Count < 1)
                return;

            if (Thread.CurrentThread != Dispatcher.CurrentDispatcher.Thread)
            {
                Dispatcher.CurrentDispatcher.Invoke(
                    DispatcherPriority.Send,
                    (DelegateInvoker)delegate
                    {
                        ForceRefresh();
                    });
                return;
            }

            base.OnCollectionChanged(new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Add, _deferredList));
            _deferredList.Clear();
        }

        #endregion

        #region OnCollectionChanged : v1

        //protected override void OnCollectionChanged(NotifyCollectionChangedEventArgs e)
        //{
        //    if (_bypassRefreshEvent)
        //        return;

        //    if (Thread.CurrentThread != Dispatcher.CurrentDispatcher.Thread)
        //    {
        //        Dispatcher.CurrentDispatcher.Invoke(
        //            DispatcherPriority.Send,
        //            (DelegateInvoker)delegate
        //            {
        //                base.OnCollectionChanged(e);
        //            });
        //        return;
        //    }

        //    base.OnCollectionChanged(e);
        //}

        #endregion

        #region OnCollectionChanged : v2 : Here is the best working version, work for Multi-core CPU

        // Based on : http://geekswithblogs.net/NewThingsILearned/archive/2008/01/16/have-worker-thread-update-observablecollection-that-is-bound-to-a.aspx
        //public override event NotifyCollectionChangedEventHandler CollectionChanged;

        //protected override void OnCollectionChanged(System.Collections.Specialized.NotifyCollectionChangedEventArgs e)
        //{
        //    if (_bypassRefreshEvent)
        //        return;

        //    // Be nice - use BlockReentrancy like MSDN said
        //    using (BlockReentrancy())
        //    {
        //        System.Collections.Specialized.NotifyCollectionChangedEventHandler eventHandler = CollectionChanged;

        //        if (eventHandler == null)
        //            return;

        //        Delegate[] delegates = eventHandler.GetInvocationList();

        //        // Walk thru invocation list
        //        foreach (System.Collections.Specialized.NotifyCollectionChangedEventHandler handler in delegates)
        //        {
        //            DispatcherObject dispatcherObject = handler.Target as DispatcherObject;

        //            // If the subscriber is a DispatcherObject and different thread
        //            if (dispatcherObject != null && dispatcherObject.CheckAccess() == false)
        //            {
        //                // Invoke handler in the target dispatcher's thread
        //                dispatcherObject.Dispatcher.Invoke(DispatcherPriority.DataBind, handler, this, e);
        //            }
        //            else // Execute handler as is
        //                handler(this, e);
        //        }
        //    }

        //}

        #endregion

        #region OnCollectionChanged : v3

        // Based on : http://geekswithblogs.net/NewThingsILearned/archive/2008/01/16/have-worker-thread-update-observablecollection-that-is-bound-to-a.aspx
        //public override event NotifyCollectionChangedEventHandler CollectionChanged;

        //protected override void OnCollectionChanged(System.Collections.Specialized.NotifyCollectionChangedEventArgs e)
        //{
        //    if (_bypassRefreshEvent)
        //        return;

        //    // Be nice - use BlockReentrancy like MSDN said
        //    using (BlockReentrancy())
        //    {
        //        System.Collections.Specialized.NotifyCollectionChangedEventHandler eventHandler = CollectionChanged;

        //        if (eventHandler == null)
        //            return;

        //        Delegate[] delegates = eventHandler.GetInvocationList();

        //        // Walk thru invocation list
        //        foreach (System.Collections.Specialized.NotifyCollectionChangedEventHandler handler in delegates)
        //        {
        //            DispatcherObject dispatcherObject = handler.Target as DispatcherObject;

        //            // If the subscriber is a DispatcherObject and different thread
        //            if (dispatcherObject != null && dispatcherObject.CheckAccess() == false)
        //            {
        //                // Invoke handler in the target dispatcher's thread
        //                dispatcherObject.Dispatcher.Invoke(DispatcherPriority.DataBind, handler, this, e);
        //                //Dispatcher.CurrentDispatcher.Invoke(
        //                //    DispatcherPriority.Send,
        //                //    (DelegateInvoker)delegate
        //                //    {
        //                //        //handler(
        //                //        base.OnCollectionChanged(e);
        //                //    });
        //            }
        //            else // Execute handler as is
        //                handler(this, e);
        //        }
        //    }

        //}

        #endregion

        #region OnCollectionChanged : v4

        //public override event NotifyCollectionChangedEventHandler CollectionChanged;
        //protected override void OnCollectionChanged(NotifyCollectionChangedEventArgs e)
        //{
        //    System.Collections.Specialized.NotifyCollectionChangedEventHandler eh = CollectionChanged;
        //    if (eh == null)
        //        return;

        //    Dispatcher dispatcher = null;
        //    foreach (NotifyCollectionChangedEventHandler handler in eh.GetInvocationList())
        //        if ((handler.Target as DispatcherObject) != null)
        //        {
        //            dispatcher = (Dispatcher)(handler.Target as DispatcherObject).Dispatcher;
        //            if (dispatcher != null)
        //                break;
        //        }

        //    //Dispatcher dispatcher = (from NotifyCollectionChangedEventHandler nh in eh.GetInvocationList()
        //    //                         let dpo = nh.Target as DispatcherObject
        //    //                         where dpo != null
        //    //                         select dpo.Dispatcher).FirstOrDefault();

        //    if (dispatcher != null && dispatcher.CheckAccess() == false)
        //    {
        //        dispatcher.Invoke(DispatcherPriority.DataBind, (Action)(() => OnCollectionChanged(e)));
        //    }
        //    else
        //    {
        //        foreach (NotifyCollectionChangedEventHandler nh in eh.GetInvocationList())
        //            nh.Invoke(this, e);
        //    }
        //}

        #endregion

        #region OnCollectionChanged : v5

        //protected override void OnCollectionChanged(NotifyCollectionChangedEventArgs e)
        //{
        //    if (_bypassRefreshEvent)
        //        return;

        //    Dispatcher.CurrentDispatcher.Invoke(
        //        DispatcherPriority.Send,
        //        (DelegateInvoker)delegate
        //        {
        //            base.OnCollectionChanged(e);
        //        });
        //}

        #endregion

        #region OnCollectionChanged : v6

        // http://tomlev2.wordpress.com/tag/mvvm/

        //private SynchronizationContext _synchronizationContext = SynchronizationContext.Current;

        //protected override void OnCollectionChanged(NotifyCollectionChangedEventArgs e)
        //{
        //    if (SynchronizationContext.Current == _synchronizationContext)
        //    {
        //        // Execute the CollectionChanged event on the current thread
        //        RaiseCollectionChanged(e);
        //    }
        //    else
        //    {
        //        // Post the CollectionChanged event on the creator thread
        //        _synchronizationContext.Post(RaiseCollectionChanged, e);
        //    }
        //}

        //private void RaiseCollectionChanged(object param)
        //{
        //    // We are in the creator thread, call the base implementation directly
        //    base.OnCollectionChanged((NotifyCollectionChangedEventArgs)param);
        //}

        //protected override void OnPropertyChanged(PropertyChangedEventArgs e)
        //{
        //    if (SynchronizationContext.Current == _synchronizationContext)
        //    {
        //        // Execute the PropertyChanged event on the current thread
        //        RaisePropertyChanged(e);
        //    }
        //    else
        //    {
        //        // Post the PropertyChanged event on the creator thread
        //        _synchronizationContext.Post(RaisePropertyChanged, e);
        //    }
        //}

        //private void RaisePropertyChanged(object param)
        //{
        //    // We are in the creator thread, call the base implementation directly
        //    base.OnPropertyChanged((PropertyChangedEventArgs)param);
        //}

        #endregion

    }
}
